package com.andnnl.guava;

import java.util.concurrent.Callable;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 任务包装
 * @param <T>
 */
public class DelayTaskWrap<T extends Callable> implements Delayed {
    private T task;
    private Object[] args;
    private Long executeTime;// ms
    private TimeUnit delayTimeUnit = TimeUnit.MILLISECONDS;
    private int runCount=0;
    /**
     * 延时执行DelayQueue的task
     *
     * @param from
     * @param args
     * @param delayTime 延时时长(毫秒)
     */
    DelayTaskWrap(T from, long delayTime, Object... args) {
        this.task = from;
        this.args = args;
        this.executeTime = System.currentTimeMillis() + delayTimeUnit.toMillis(delayTime);
    }

    /**
     * 延时执行DelayQueue的task
     *
     * @param from
     * @param delayTime 延时时长(毫秒)
     */
    DelayTaskWrap(T from, long delayTime) {
        this.task = from;
        this.executeTime = System.currentTimeMillis() + delayTimeUnit.toMillis(delayTime);
    }

    @Override
    public int compareTo(Delayed o) {
        if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {
            return 1;
        } else if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {
            return -1;
        }
        return 0;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(executeTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }


    public T getTask() {
        return task;
    }

    public Object[] getArgs() {
        return args;
    }

    public void setArgs(Object[] args) {
        this.args = args;
    }

    public int getRunCount() {
        return runCount;
    }
}